<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/4/27
 * Time: 17:20
 */

namespace Api\Controller;

use Think\Controller;
use Think\Log;


class StockController extends Controller {

    // log日志
    private $logFile;

    // 构造函数
    public function  __construct()
    {
        $this->logFile = C('LOG_PATH') . 'Api_stock_' . date('y_m_d') . '.log';
    }

    //仓库
    public function addStock(){

        // 添加日志，记录原始接收到的OMS的数据，Powered by liuzongyang 2019/10/9 11:11
        $message = '现在正在记录OMS发送过来的addStock Request的数据，请知悉： ' . PHP_EOL;
        $message .= 'OMS发送过来的addStock Request的信息如下: ' . PHP_EOL;
        $message .= print_r($GLOBALS['HTTP_RAW_POST_DATA'], true);
        Log::write($message, 'debug', '', $this->logFile);

        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace('"[','[',$GLOBALS['HTTP_RAW_POST_DATA']);
//        $GLOBALS['HTTP_RAW_POST_DATA'] = str_replace(']"',']',$GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
//        $_POST = json_decode('{
//  "ClientGuid": "string",
//  "ClientName": "string",
//  "Warehouse": {
//    "ChannelId": "12",
//    "ChannelName": "string",
//    "Local": "string",
//    "VendorId": "2",
//    "VendorName": "string",
//    "TradeType": "1",
//    "IfAdmin": "1",
//    "GroupId": "122"
//  }
//}
//',true);
        if(!$_POST['Warehouse'] || !is_array($_POST['Warehouse'])) {
            $return_array = array(
                'MessageCode' => '2',
                'Method' => 'ReceiveVendor',
                'ErrorMsg' => '参数错误',
            );
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
            exit;
        }
//        $rules = array(
//            array('ChannelId','required','报关通道id不能为空！'),
//            array('ChannelName','required','报关通道名称不能为空！'),
//            array('Local','required','所在地不能为空！'),
//            array('VendorId','required','供应商id不能为空！'),
//            array('VendorName','required','供应商不能为空'),
//            array('TradeType','required','贸易方式不能为空'),
//            array('IfAdmin','required','是否ASA自有仓库不能为空'),
//            array('GroupId','required','组合码不能为空'),
//
//            array('ChannelId','','报关通道id已存在！',0,'unique',1),
//            array('GroupId','','组合码已经存在！',0,'unique',1),
//        );
        $stock_model = M("Storestock");
//        if (!$stock_model->validate($rules)->create(json_decode())){
//            // 如果创建失败 表示验证没有通过 输出错误提示信息
//            $return_array = array(
//                'MessageCode' => '2',
//                'Method' => 'ReceiveVendor',
//                'ErrorMsg' => $stock_model->getError(),
//            );
//            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
//            exit;
//        }
        $cond['storestock_id'] = $_POST['Warehouse']['GroupId'];
        $resSelect = $stock_model->where($cond)->find();
        if(!$resSelect){
            $data = array(
                'stock_id' => $_POST['Warehouse']['ChannelId'],
                'stock_name' => $_POST['Warehouse']['ChannelName'],
                'stock_place' => $_POST['Warehouse']['Local'],
                'store_id' => $_POST['Warehouse']['VendorId'],
                'store_name' => $_POST['Warehouse']['VendorName'],
                'stock_style' => $_POST['Warehouse']['TradeType'],
                'if_admin' => $_POST['Warehouse']['IfAdmin'],
                'storestock_id' => $_POST['Warehouse']['GroupId'],
            );
            $res = $stock_model -> add($data);
        }else{
            $data = array(
                'stock_id' => $_POST['Warehouse']['ChannelId'],
                'stock_name' => $_POST['Warehouse']['ChannelName'],
                'stock_place' => $_POST['Warehouse']['Local'],
                'store_id' => $_POST['Warehouse']['VendorId'],
                'store_name' => $_POST['Warehouse']['VendorName'],
                'stock_style' => $_POST['Warehouse']['TradeType'],
                'if_admin' => $_POST['Warehouse']['IfAdmin'],
            );
            $res = $stock_model -> where($cond) -> save($data);
        }

        if($res === false){
            $return_array = array(
                'MessageCode' => '2',
                'Method' => 'ReceiveVendor',
                'ErrorMsg' => '添加失败',
            );
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
            exit;
        }
        $return_array = array(
            'MessageCode' => '1',
            'Method' => 'ReceiveVendor',
            'ErrorMsg' => '添加成功',
        );
        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
        exit;
    }

    //库存
    public function addReserve(){
        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        if(!$_POST || !is_array($_POST)) {
            $return_array = array(
                'Result' => '2',
                'Msg' => '参数错误',
            );
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
            exit;
        }
        $model_spec = M('goods_spec');
        $return_array = array();
        foreach ($_POST as $key => $value){
            $model_spec->startTrans();
            //查询仓库
            $cond = array(
                'storestock_id' => $value['StoreId'] . $value['WarehouseId']
            );
            $res = M('storestock')->where($cond)->find();
            if(!$res){
                $model_spec -> rollback();
                $return_array[] = array(
                    'Result' => '2',
                    'Id' => $value['Id'],
                    'Msg' => '查找仓库'.$value['StoreId'] . $value['WarehouseId'].'失败',
                );
                continue;
            }
            //是否有税
            $tax_price = 0;
            if($res['stock_style'] == 3){
                $tax_price = 0;
            }
            //condition1: SKU+仓库ID
            $cond1 = array(
                'sku' => $value['Sku'],
                'spec_3value' => $value['StoreId'] . $value['WarehouseId']
            );
            $res_condition1 = $model_spec -> where($cond1) -> find();
            //直接编辑库存
            if($res_condition1){
                if($res['stock_style'] != 3){
                    //查询订单tax_id
                    $res_goods = M('goods')->where(array('goods_id'=>$res_condition1['goods_id']))->find();
                    if(!$res_goods){
                        $model_spec -> rollback();
                        $return_array[] = array(
                            'Result' => '2',
                            'Id' => $value['Id'],
                            'Msg' => '商品详情'.$res_goods,
                        );
                        continue;
                    }
                    //查出综合税
                    $res_tax = M('myTax')->where(array('tax_id'=>$res_goods['tax_id']))->find();
                    if(!$res_tax){
                        $return_array[] = array(
                            'Result' => '2',
                            'Id' => $value['Id'],
                            'Msg' => '查找综合税失败',
                        );
                        continue;
                    }
                    $tax_price = round($res_tax['consolidated_tax'] * $value['Price'],2);
                }
                $data = array(
                    'stock' =>  $value['AvailableQuantity'],
                    'price' => $value['Price'],
                    'tax_price' => $tax_price
                );

                $res_edit1 = $model_spec -> where($cond1) -> save($data);
                if($res_edit1 === false){
                    $model_spec -> rollback();
                    $return_array[] = array(
                        'Result' => '2',
                        'Id' => $value['Id'],
                        'Msg' => '编辑失败',
                    );
                    continue;
                }else{
                    $model_spec -> commit();
                    $return_array[] = array(
                        'Result' => '1',
                        'Id' => $value['Id'],
                        'Msg' => '编辑成功1--库存为：'.$data['stock'].'--价格为：'.$data['price'],
                    );
                    continue;
                }
            }else{
                //condition2: SKU
                $cond2 = array(
                    'sku' => $value['Sku'],
                );
                $res_condition2 = $model_spec -> where($cond2) -> find();
                if(!$res_condition2 || !$res_condition2['spec_1']){


                    //新条件 查询国际码
//                    $international_code = preg_replace("/(.*)(\|+)(.*)/iU",'$1',$value['Sku']);
                    $international_code = explode("|",$value['Sku']);
                    $spec_2 = preg_replace("/(.*)(\|+)(.*)/iU",'$3',$value['Sku']);
                    $res_code = M('goods_spec')->where(array('international_code'=>$international_code[0]))->find();
                    if(!$res_code){
                        $model_spec -> rollback();
                        $return_array[] = array(
                            'Result' => '2',
                            'Id' => $value['Id'],
                            'Msg' => '查找sku失败',
                        );
                        continue;
                    }else{
                        if($res['stock_style'] != 3){
                            //查询订单tax_id
                            $res_goods = M('goods')->where(array('goods_id'=>$res_code['goods_id']))->find();
                            if(!$res_goods){
                                $model_spec -> rollback();
                                $return_array[] = array(
                                    'Result' => '2',
                                    'Id' => $value['Id'],
                                    'Msg' => '商品详情'.$res_goods,
                                );
                                continue;
                            }
                            //查出综合税
                            $res_tax = M('myTax')->where(array('tax_id'=>$res_goods['tax_id']))->find();
                            if(!$res_tax){
                                $return_array[] = array(
                                    'Result' => '2',
                                    'Id' => $value['Id'],
                                    'Msg' => '查找综合税失败',
                                );
                                continue;
                            }
                            $tax_price = round($res_tax['consolidated_tax'] * $value['Price'],2);
                        }

                        $data_add = array(
                            'goods_id' => $res_code['goods_id'],
                            'spec_1' => $res_code['spec_1'],
                            'spec_1value' => $res_code['spec_1value'],
                            'spec_2' => $spec_2,
                            'price' => $value['Price'],
                            'tax_price' => $tax_price,
                            'stock' => $value['AvailableQuantity'],
                            'sku' => $value['Sku'],
                            'barcode' => $res_code['barcode'],
                            'spec_3' => $res['stock_name'],
                            'spec_3value' => $value['StoreId'] . $value['WarehouseId'],
                            'spec_4' => $res_code['spec_4'],
                            'international_code' => $international_code[0],
                        );
                        $res_add = $model_spec -> add($data_add);
                        if(!$res_add){
                            $model_spec -> rollback();
                            $return_array[] = array(
                                'Result' => '2',
                                'Id' => $value['Id'],
                                'Msg' => '添加失败',
                            );
                            continue;
                        }else{
                            $model_spec -> commit();
                            $return_array[] = array(
                                'Result' => '1',
                                'Id' => $value['Id'],
                                'Msg' => '添加成功',
                            );
                            continue;
                        }
                    }
                }else{
                    //condition3: SKU 仓库ID为0
                    $cond3 = array(
                        'sku' => $value['Sku'],
                        'spec_3value' => 0,
                    );
                    $res_condition3 = $model_spec -> where($cond3) -> find();
                    if($res['stock_style'] != 3){
                        //查询订单tax_id
                        $res_goods = M('goods')->where(array('goods_id'=>$res_condition2['goods_id']))->find();
                        if(!$res_goods){
                            $model_spec -> rollback();
                            $return_array[] = array(
                                'Result' => '2',
                                'Id' => $value['Id'],
                                'Msg' => '商品详情有误',
                            );
                            continue;
                        }
                        //查出综合税
                        $res_tax = M('myTax')->where(array('tax_id'=>$res_goods['tax_id']))->find();
                        if(!$res_tax){
                            $return_array[] = array(
                                'Result' => '2',
                                'Id' => $value['Id'],
                                'Msg' => '查找综合税失败',
                            );
                            continue;
                        }
                        $tax_price = round($res_tax['consolidated_tax'] * $value['Price'],2);

                    }

                    if(!$res_condition3){
                        $international_code = explode("|",$value['Sku']);
                        $data_add = array(
                           'goods_id' => $res_condition2['goods_id'],
                           'spec_1' => $res_condition2['spec_1'],
                           'spec_1value' => $res_condition2['spec_1value'],
                           'spec_2' => $res_condition2['spec_2'],
                           'price' => $value['Price'],
                           'tax_price' => $tax_price,
                           'stock' => $value['AvailableQuantity'],
                           'sku' => $res_condition2['sku'],
                           'barcode' => $res_condition2['barcode'],
                           'spec_3' => $res['stock_name'],
                           'spec_3value' => $value['StoreId'] . $value['WarehouseId'],
                           'spec_4' => $res_condition2['spec_4'],
                           'international_code' => $international_code[0],
                       );
                       $res_add = $model_spec -> add($data_add);
                       if(!$res_add){
                           $model_spec -> rollback();
                           $return_array[] = array(
                               'Result' => '2',
                               'Id' => $value['Id'],
                               'Msg' => '添加失败',
                           );
                           continue;
                       }else{
                           $model_spec -> commit();
                           $return_array[] = array(
                               'Result' => '1',
                               'Id' => $value['Id'],
                               'Msg' => '添加成功',
                           );
                           continue;
                       }
                    }else{
                        $data_edit = array(
                            'spec_1' => $res_condition2['spec_1'],
                            'spec_1value' => $res_condition2['spec_1value'],
                            'stock' => $value['AvailableQuantity'],
                            'price' => $value['Price'],
                            'tax_price' => $tax_price,
                            'spec_3' => $res['stock_name'],
                            'spec_3value' => $value['StoreId'] . $value['WarehouseId'],
                        );
                        $res_edit = $model_spec -> where($cond3)->save($data_edit);
                        if($res_edit === false){
                            $model_spec -> rollback();
                            $return_array[] = array(
                                'Result' => '2',
                                'Id' => $value['Id'],
                                'Msg' => '编辑失败2',
                            );
                            continue;
                        }else{
                            $model_spec -> commit();
                            $return_array[] = array(
                                'Result' => '1',
                                'Id' => $value['Id'],
                                'Msg' => '编辑成功2',
                            );
                            continue;
                        }
                    }
                }

            }
        }

        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
        exit;

    }
    public function addReserveCopy()
    {

        // 添加日志，记录原始接收到的OMS的数据，Powered by liuzongyang 2019/10/9 11:12
        $message = '现在正在记录OMS发送过来的addReserveCopy Request的数据，请知悉： ' . PHP_EOL;
        $message .= 'OMS发送过来的addReserveCopy Request的信息如下: ' . PHP_EOL;
        $message .= print_r($GLOBALS['HTTP_RAW_POST_DATA'], true);
        Log::write($message, 'debug', '', $this->logFile);

        $GLOBALS['HTTP_RAW_POST_DATA'] = stripslashes($GLOBALS['HTTP_RAW_POST_DATA']);
        $_POST = json_decode($_POST['string'],true);
        if(!$_POST || !is_array($_POST)) {
            $return_array = $this->ApiReturn(2,array(),'参数错误');
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
            exit;
        }
        $model_spec = M('goods_spec');
        $return_array = array();
        try{
            $model_spec->startTrans();
            foreach($_POST as $value){
                //condition2: SKU
                $res_condition2 = $model_spec -> where(array('sku'=>$value['Sku'])) -> find();
                if(!$res_condition2 || !$res_condition2['spec_1']){
                    $model_spec -> rollback();
                    $return_array = $this->ApiReturn(2,$value['Id'],'查找sku失败');
                    continue;
                }
                //查询仓库
                $res = M('storestock')->where(array('storestock_id'=>$value['StoreId'] . $value['WarehouseId']))->find();
                if(!$res){
                    $model_spec -> rollback();
                    $return_array = $this->ApiReturn(2,$value['Id'],'查找仓库失败');
                    continue;
                }
                //是否有税
                $tax_price = 0;
                if($res['stock_style'] == 3){
                    $tax_price = 0;
                }
                //condition1: SKU+仓库ID
                $cond1 = array(
                    'sku' => $value['Sku'],
                    'spec_3value' => $value['StoreId'] . $value['WarehouseId']
                );
                $res_condition1 = $model_spec -> where($cond1) -> find();
                //直接编辑库存
                if($res_condition1){
                    if($res['stock_style'] != 3){
                        //查询订单tax_id
                        $res_goods = M('goods')->where(array('goods_id'=>$res_condition1['goods_id']))->find();
                        if(!$res_goods){
                            $model_spec -> rollback();
                            $return_array = $this->ApiReturn(2,$value['Id'],'查找订单失败');
                            continue;
                        }
                        //查出综合税
                        $res_tax = M('myTax')->where(array('tax_id'=>$res_goods['tax_id']))->find();
                        if(!$res_tax){
                            $return_array = $this->ApiReturn(2,$value['Id'],'查找综合税失败');
                            continue;
                        }
                        $tax_price = round($res_tax['consolidated_tax'] * $value['Price'],2);
                    }
                    $data = array(
                        'stock' =>  $value['AvailableQuantity'],
                        'price' => $value['Price'],
                        'tax_price' => $tax_price
                    );
                    $res_edit1 = $model_spec -> where($cond1) -> save($data);
                    if($res_edit1 === false){
                        $model_spec -> rollback();
                        $return_array = $this->ApiReturn(2,$value['Id'],'编辑失败');
                        continue;
                    }else{
                        $model_spec -> commit();
                        $return_array = $this->ApiReturn(1,$value['Id'],'编辑成功');
                        continue;
                    }
                }else{
                    //condition3: SKU 仓库ID为0
                    $cond3 = array(
                        'sku' => $value['Sku'],
                        'spec_3value' => 0,
                    );
                    $res_condition3 = $model_spec -> where($cond3) -> find();
                    if($res['stock_style'] != 3){
                        //查询订单tax_id
                        $res_goods = M('goods')->where(array('goods_id'=>$res_condition1['goods_id']))->find();
                        if(!$res_goods){
                            $model_spec -> rollback();
                            $return_array = $this->ApiReturn(2,$value['Id'],'查找订单失败');
                            continue;
                        }
                        //查出综合税
                        $res_tax = M('myTax')->where(array('tax_id'=>$res_goods['tax_id']))->find();
                        if(!$res_tax){
                            $return_array = $this->ApiReturn(2,$value['Id'],'查找综合税失败');
                            continue;
                        }
                        $tax_price = round($res_tax['consolidated_tax'] * $value['Price'],2);
                    }
                    if(!$res_condition3){
                        $data_add = array(
                            'goods_id' => $res_condition2['goods_id'],
                            'spec_1' => $res_condition2['spec_1'],
                            'spec_1value' => $res_condition2['spec_1value'],
                            'spec_2' => $res_condition2['spec_2'],
                            'price' => $value['Price'],
                            'tax_price' => $tax_price,
                            'stock' => $value['AvailableQuantity'],
                            'sku' => $res_condition2['sku'],
                            'barcode' => $res_condition2['barcode'],
                            'spec_3' => $res['stock_name'],
                            'spec_3value' => $value['StoreId'] . $value['WarehouseId'],
                            'spec_4' => $res_condition2['spec_4'],
                        );
                        $res_add = $model_spec -> add($data_add);
                        if(!$res_add){
                            $model_spec -> rollback();
                            $return_array = $this->ApiReturn(2,'','添加失败');
                            continue;
                        }else{
                            $model_spec -> commit();
                            $return_array = $this->ApiReturn(1,$value['Id'],'添加成功');
                            continue;
                        }
                    }else{
                        $data_edit = array(
                            'spec_1' => $res_condition2['spec_1'],
                            'spec_1value' => $res_condition2['spec_1value'],
                            'stock' => $value['AvailableQuantity'],
                            'price' => $value['Price'],
                            'tax_price' => $tax_price,
                            'spec_3' => $res['stock_name'],
                            'spec_3value' => $value['StoreId'] . $value['WarehouseId'],
                        );
                        $res_edit = $model_spec -> where($cond3)->save($data_edit);
                        if($res_edit === false){
                            $model_spec -> rollback();
                            $return_array = $this->ApiReturn(2,$value['Id'],'编辑失败');
                            continue;
                        }else{
                            $model_spec -> commit();
                            $return_array = $this->ApiReturn(2,$value['Id'],'编辑成功');
                            continue;
                        }
                    }
                }
            }
        }catch(\Exception $e){
            $return_array = $this->ApiReturn(2,'','网络错误');
            echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
        }
        echo json_encode($return_array, JSON_UNESCAPED_UNICODE);
        exit;
    }

    private function ApiReturn($code,$data=null,$msg)
    {
        $return_array[] = array(
            'Result' => $code,
            'Id' => $data,
            'Msg' => $msg,
        );
        return $return_array;
    }
}
